<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>出库单导入</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<jsp:include page="${pageContext.request.contextPath }/resource_path.jsp" flush="true"/>
</head>
<body class="layui-anim layui-anim-up">
	<%--隐藏选中行的id--%>
	<input class="layui-hide" id="firstTableId">
    <div class="x-nav">
      <span class="layui-breadcrumb">
        <a href="">首页</a>
        <a>
          <cite>出库单导入</cite>
        </a>
      </span>
    </div>
    <div class="x-body">
      <div style="margin-bottom: 18px">
		<div class="layui-inline">
			<table>
				<tr>
					<td>
						<!-- 
							<div class="layui-form" style="width: 180px; margin-left: 10px">
								<select id="keyword01">
									<option value="">请选择出库状态</option>
									<option>已出库</option>
									<option>未出库</option>
								</select>
							</div> 
						-->
						<input class="layui-input" id="keyword01" style="width: 210px; margin-left: 10px" placeholder="请选择年月">
					</td>
					<!-- 
					<td>
						<input class="layui-input" id="keyword02" style="width: 210px; margin-left: 10px" placeholder="请选择日期范围查询">
					</td> 
					-->
				</tr>
			</table>
		</div>
        <button class="layui-btn layui-btn-normal" data-type="reload"><i class="layui-icon layui-icon-search"></i>检索</button>
	  </div>
      <xblock>
			<button id="add" class="layui-btn layui-btn-warm"><i class="layui-icon layui-icon-add-circle-fine"></i>新增出库单</button>
			<button id="dels" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
			<!-- <button class="layui-btn layui-btn-blue" onclick="uploadExcel()"><i class="layui-icon layui-icon-down"></i>出库单导入</button> -->
      </xblock> 
	  <table class="layui-hide" id="tableList" lay-filter="tableList"></table>
	</div>
	<div id="addTwoFormIDDiv" hidden="hidden">
		<form class="layui-form" id="addTwoFormID">
			<table class="layui-hide" id="customerList" lay-filter="customerList"></table>
			<table class="layui-hide" id="customerMaterielList" lay-filter="customerMaterielList"></table>
			<button class="layui-btn layui-btn-blue" id="addBtn" lay-submit lay-filter="addBtn" style="margin-left:350px; margin-bottom: 10px; width: 300px">添加</button>
		</form>
	</div>
	<!-- _____________________________________子表________________________________________ -->
	<div id="subTable" hidden="hidden">
		<xblock>
			<button id="add1" class="layui-btn layui-btn-warm"><i class="layui-icon layui-icon-add-circle-fine"></i>选择物料</button>
			<button id="dels1" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
			<!-- <button class="layui-btn layui-btn-blue" onclick="uploadExcel()"><i class="layui-icon layui-icon-down"></i>出库单导入</button> -->
      </xblock>
	  <table class="layui-hide" id="tableListSub" lay-filter="tableListSub"></table>
	</div>
	<script type="text/html" id="rowToolbar">
		<a class="layui-btn layui-btn-xs" lay-event="update"><i class="layui-icon layui-icon-edit"></i>编辑</a>
	</script>
	<script type="text/html" id="rowToolbar2">
		<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del2"><i class="layui-icon layui-icon-delete"></i>删除</a>
	</script>
	<!-- 导入框 -->
	<div id="importDiv" hidden="hidden">
		<form class="layui-form" id="uploadform">
			<div style="margin: 20px 0 20px 140px;">
				<input id="fileInput" name="file" type="file" accept=".xls,.xlsx"/>
			</div>
		</form>
		<button class="layui-btn layui-btn-blue" lay-filter="uplodeform" style="margin-left: 80px">导入数据</button>&emsp;&emsp;&emsp;&emsp;
		<button type="button" class="layui-btn" id="downloadFile">下载模板</button>
	</div>

	<script type="text/javascript">
        var table;
		layui.use(['table','layer','upload','form','laydate'], function(){
			table = layui.table;
			var layer = layui.layer;
			var form = layui.form;
			var laydate = layui.laydate;
			var $ = layui.jquery, active = {
				reload:function () {
					var keyword01 = $("#keyword01").val();
					//var keyword02 = $("#keyword02").val();
					//var keyword03 = $("#keyword03").val();
					table.reload('contenttable',{
						method:'get',
						where:{"keyword01":keyword01}
					});
				}
			}
			$('.layui-btn').on('click', function(){
				var type = $(this).data('type');
				active[type] ? active[type].call(this) : '';
			});
			table.render({
				elem: '#tableList'
				,url:'${pageContext.request.contextPath }/stockOutOrder/queryOutStockOrderCriteria.do'
				,toolbar: '#toolbar'
				,title: 'machineList'
				,id :'contenttable'
				,limits:[10,20,30]
                ,defaultToolbar:['filter', 'print']
				,cols: [[
					{type: 'checkbox', fixed: 'left', },
				  	{field:'', title:'序号', type:'numbers', align:'center'},
				  	{field:'out_stock_num', title:'出库单号', align:'center'},
				  	{field:'create_date', title:'创建时间', align:'center'},
				  	{field:'warehouse_name', title:'仓库名称', align:'center'},
				  	{field:'warehouse_address', title:'仓库地址', align:'center'},
				  	{field:'userName', title:'仓库管理员', align:'center'},
				  	{field:'phone', title:'管理员电话', align:'center'},
				  	{field:'customer_name', title:'主机厂名称', align:'center'},
				  	{field:'customer_adress', title:'主机厂地址', align:'center'},
				  	{field:'contacts_name', title:'主机厂负责人', align:'center'},
				 	{field:'contacts_tel', title:'负责人电话', align:'center'},
				  	{field:'status', title:'状态', align:'center', templet: function (row){
   	                    if (row.status == '0') {
   	                        return "未出库";
   	                    } else {
   	                        return "已出库";
   	                    }
   	                }},
				  	{fixed:'right',unresize: true, title:'操作', toolbar: '#rowToolbar',width:100, align: 'center'}
			  	]]
				,page: true
                ,done : function(){
                    $(".timepicker").each(function () {
						laydate.render({
							elem: this,
							format: "yyyy-MM-dd"
						});
					});
                    $('th').css({
                        'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                    })
                }
			});

			//出库单的编辑
			table.on('tool(tableList)', function(obj){
				var data = obj.data;
				if(obj.event === 'update'){
					layer.open({
						type: 1 				//Page层类型
						,area: ['680px', ''] 	//宽  高
						,title: '编辑'
						,shade: 0.1 			//遮罩透明度
						,maxmin: true 			//允许全屏最小化
						,anim: 1 				//0-6的动画形式，-1不开启
						,content: 
						'<div id="updateDivID">'+
							'<form class="layui-form" id="updateFormID">'+
								'<xblock>'+
									'<table>'+
										'<tr>'+
											'<td>'+
												'<input class="layui-hide" name="id" value="'+data.id+'">'+
											'</td>'+
										'</tr>'+
										'<tr>'+
											'<td><label class="layui-form-label">出库单号</label></td>'+
											'<td>'+
												'<input readonly class="layui-input" id="out_stock_num" name="out_stock_num" value="'+data.out_stock_num+'" style="color: gray; width: 190px">'+
											'</td>'+
											'<td><label class="layui-form-label">创建日期</label></td>'+
											'<td>'+
												'<input class="layui-input" id="create_date" name="create_date" value="'+data.create_date+'" lay-verify="create_date" style="width: 190px; display:inline" placeholder="请选择">'+
												'<div class="layui-inline" style="margin-top: 10px;">'+
		                                            '<span style="color:red; font-size: 24px; margin-left: 4px">*</span>'+
		                                        '</div>'+
											'</td>'+
										'</tr>'+
										'<tr style="height: 10px"></tr>'+
										'<tr>'+
											'<td><label class="layui-form-label">仓库类型</label></td>'+
											'<td>'+
												'<div style="width: 190px; float: left;">' +
													'<select id="source" name="source" lay-verify="source">' +
														'<option value="">请选择</option>' +
														'<option value="0">良品库</option>' +
														'<option value="1">不良品库</option>' +
													'</select>'+
			                                    '</div>'+
			                                    '<div style="margin-top: 12px;">'+
			                                        '<span style="color:red; font-size: 24px; margin-left: 4px">*</span>'+
			                                    '</div>'+
											'</td>'+
											'<td><label class="layui-form-label">仓库名称</label></td>'+
											'<td>'+
												'<div style="width: 190px; float: left;">' +
													'<select id="warehouse_id" name="warehouse_id" lay-verify="warehouse_id" lay-filter="warehouse_id">' +
														'<option value="">请选择</option>' +
													'</select>'+
			                                    '</div>'+
			                                    '<div style="margin-top: 12px;">'+
			                                        '<span style="color:red; font-size: 24px; margin-left: 4px">*</span>'+
			                                    '</div>'+
											'</td>'+
										'</tr>'+
										'<tr style="height: 10px"></tr>'+
										'<tr>'+
											'<td><label class="layui-form-label">管理员姓名</label></td>'+
											'<td>'+
												'<input class="layui-input" id="userName" name="userName" value="'+data.userName+'" style="width: 190px; display:inline" placeholder="请选择">'+
											'</td>'+
											'<td><label class="layui-form-label">管理员电话</label></td>'+
											'<td>'+
												'<input class="layui-input" id="phone" name="phone" value="'+data.phone+'" style="width: 190px; display:inline" placeholder="请选择">'+
											'</td>'+
										'</tr>'+
										'<tr style="height: 10px"></tr>'+
										'<tr>'+
											'<td><label class="layui-form-label">仓库地址</label></td>'+
											'<td>'+
												'<input class="layui-input" id="warehouse_address" name="warehouse_address" value="'+data.warehouse_address+'" style="width: 190px; display:inline" placeholder="请选择">'+
											'</td>'+
											'<td><label class="layui-form-label">主机厂名称 </label></td>'+
											'<td>'+
												'<div style="width: 190px; float: left;">' +
			                                        '<select id="customer_id" name="customer_id" lay-verify="customer_id" lay-filter="customer_id">' +
			                                            '<option value="">请选择</option>' +
			                                        '</select>'+
			                                    '</div>'+
			                                    '<div style="margin-top: 12px;">'+
			                                        '<span style="color:red; font-size: 24px; margin-left: 4px">*</span>'+
			                                    '</div>'+
											'</td>'+
										'</tr>'+
										'<tr style="height: 10px"></tr>'+
										'<tr>'+
											'<td><label class="layui-form-label">负责人</label></td>'+
											'<td>'+
												'<input readonly class="layui-input" id="contacts_name" name="contacts_name" value="'+data.contacts_name+'" style="width: 190px; display:inline">'+
											'</td>'+
											'<td><label class="layui-form-label">负责人电话</label></td>'+
											'<td>'+
												'<input readonly class="layui-input" id="contacts_tel" name="contacts_tel" value="'+data.contacts_tel+'" style="width: 190px; display:inline">'+
											'</td>'+
										'</tr>'+
		                				'<tr style="height: 10px"></tr>'+
										'<tr>'+
											'<td><label class="layui-form-label">客户地址</label></td>'+
											'<td colspan="3">'+
												'<input readonly class="layui-input" id="customer_adress" name="customer_adress" value="'+data.customer_adress+'" style="width: 490px; display:inline">'+
											'</td>'+
										'</tr>'+
									'</table>'+
								'</xblock>'+
								'<xblock>'+
									'<button class="layui-btn layui-btn-blue" id="subBtn" lay-submit lay-filter="updateForm" style="margin-left:250px; margin-bottom: 10px">提交</button>'+
									'&emsp;&emsp;&emsp;&emsp;<button class="layui-btn layui-btn-primary" style="margin-bottom: 10px">取消</button>'+
								'</xblock>'+
								'</table>'+
							'</form>'+
                    	'</div>'
						,success: function () {
							//仓库类型回显
							
							//查找所有仓库
	                    	$.ajax({ 
	                            type: 'POST',
	                            url: '${pageContext.request.contextPath}/warehouse/queryAllWarehouse.do',
	                            dataType: 'json',
	                            async: false,
	                            success: function (datas){
	                                for (var i = 0; i < datas.length; i++) {
	                                	$("#warehouse_id").append("<option value='"+ datas[i].id +"'>"+ datas[i].warehouse_name +"</option>");
	                                	if(datas[i].id == data.warehouse_id){
		                                    $("#warehouse_id").val(data.warehouse_id);
		                                }
	                                }
	                            }
	                        });
	                    	//查找所有客户/主机厂
	                    	$.ajax({ 
	                            type: 'POST',
	                            url: '${pageContext.request.contextPath}/stockOutOrder/queryAllCustomerByType1.do',
	                            dataType: 'json',
	                            async: false,
	                            success: function (datas){
	                                for (var i = 0; i < datas.length; i++) {
	                                	$("#customer_id").append("<option value='"+ datas[i].id +"'>"+ datas[i].customer_name +"</option>");
	                                	if(datas[i].id == data.customer_id){
		                                    $("#customer_id").val(data.customer_id);
		                                }
	                                }
	                            }
	                        });
	                        laydate.render({
	                            elem: '#create_date'
	                        });
	                        form.render();
						}
					});
				}
			});

			/* var mIdArr = new Array();
			//监听待发货区表的checkbox选中事件
            table.on('checkbox(waitSendAreaMateriel)', function(obj){
                //选中行的大表id
                //alert($("#firstTableId").val());
                //选中行的
				//alert(obj.data.id);
                mIdArr.push(obj.data.id);
            });
			//监听库存表的checkbox选中事件
            table.on('checkbox(zcInventoryInfoMateriel)', function(obj){
                mIdArr.push(obj.data.id);
            }); */

          	//供应商列表行单击事件
            table.on('row(customerList)', function(obj) {
            	var data = obj.data;
            	//mIdArr.push(data.id);
            	table.render({
                    elem: '#customerMaterielList'
                    //根据供应商id查询该供应商的所有物料
                    ,url:'${pageContext.request.contextPath }/customer/queryInventoryInfoByCustomerId.do?id='+data.id
                    ,toolbar: '#toolbar'
                    ,title: '出库单详细表'
                    ,id :'contenttable2'
                    ,limits:[10,20,30]
                    ,defaultToolbar:['filter', 'print']
                    ,cols: [[
						{type: 'checkbox', fixed: 'left', },
						{field:'materiel_name', title:'物料名称', align:'center'},
						{field:'materiel_num', title:'产品码', align:'center'},
						{field:'brevity_num', title:'物料简码', align:'center'},
						{field:'materiel_size', title:'物料规格', align:'center'},
						{field:'materiel_properties', title:'物料型号', align:'center'},
						{field:'sequence_number', title:'待发货区数量', align:'center'},
						{field:'placement_type', title:'库存中小箱数', align:'center'}
     				]]
                    ,page: false
                    ,done : function(){
                        $('th').css({
                            'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                        })
                    }
                });
            });
            
            //出库单行单击事件
            table.on('row(tableList)', function(obj) {
            	$("#subTable").show();
                var data = obj.data;
                //单击每一行的时候将该行的id传入
                //mIdArr.push(data.id);
                $("#firstTableId").val(data.id);
                table.render({
                    elem: '#tableListSub'
                    ,url:'${pageContext.request.contextPath }/stockOutOrder/queryOutStockOrderCriteriaById.do?keyword01='+data.id
                    ,toolbar: '#toolbar'
                    ,title: '出库单详细表'
                    ,id :'contenttable1'
                    ,limits:[10,20,30]
                    ,defaultToolbar:['filter', 'print']
                    ,cols: [[
	   				  	{type: 'checkbox', fixed: 'left', },
	   				  	{field:'customer_name', title:'供应商名称', hide:true},
	   				  	{field:'materiel_name', title:'物料名称', align:'center'},
	   				 	{field:'materiel_num', title:'产品码', align:'center'},
		   				{field:'brevity_num', title:'物料简码', align:'center'},
		   				{field:'materiel_size', title:'物料规格', align:'center'},
		   				{field:'materiel_properties', title:'物料型号', align:'center'},
	   				  	{field:'material_quantity', title:'物料数量', align:'center', edit: true, templet: function (row){
							return '<span style="color: blue">'+row.material_quantity+'</span>';
						}},
	   				  	{field:'actual_quantity', title:'实际数量', align:'center'},
	   				  	/* {field:'status', title:'状态', align:'center', templet: function (row){
	   	                    if (row.status == '0') {
	   	                        return "未退库";
	   	                    } else {
	   	                        return "已退库";
	   	                    }
	   	                }}, */
     				]]
                    ,page: true
                    ,done : function(){
                        $('th').css({
                            'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                        })
                    }
                });
            });

          	//点击行checkbox选中
    	    $(document).on("click",".layui-table-body table.layui-table tbody tr", function () {
    	        var index = $(this).attr('data-index');
    	        var tableBox = $(this).parents('.layui-table-box');
    	        //存在固定列
    	        if (tableBox.find(".layui-table-fixed.layui-table-fixed-l").length>0) {
    	            tableDiv = tableBox.find(".layui-table-fixed.layui-table-fixed-l");
    	        } else {
    	            tableDiv = tableBox.find(".layui-table-body.layui-table-main");
    	        }
    	        var checkCell = tableDiv.find("tr[data-index=" + index + "]").find("td div.laytable-cell-checkbox div.layui-form-checkbox I");
    	        if (checkCell.length>0) {
    	            checkCell.click();
    	        }
    	    });
    	
    	    $(document).on("click", "td div.laytable-cell-checkbox div.layui-form-checkbox", function (e) {
    	        e.stopPropagation();
    	    });
            
            //监听复选框事件
            table.on('checkbox(tableList)',function(obj){
                if(obj.checked == true && obj.type == 'all'){
                    //点击全选
                    $('.layui-table-body table.layui-table tbody tr').addClass('layui-table-click');
                }else if(obj.checked == false && obj.type == 'all'){
                    //点击全不选
                    $('.layui-table-body table.layui-table tbody tr').removeClass('layui-table-click');
                }else if(obj.checked == true && obj.type == 'one'){
                    //点击单行
                    if(obj.checked == true){
                        obj.tr.addClass('layui-table-click');
                    }else{
                        obj.tr.removeClass('layui-table-click');
                    }
                }else if(obj.checked == false && obj.type == 'one'){
                    //点击全选之后点击单行
                    if(obj.tr.hasClass('layui-table-click')){
                        obj.tr.removeClass('layui-table-click');
                    }
                }
            })

            laydate.render({
				elem: '#keyword01',
			});
            
            $('#downloadFile').click(function(){
                layer.confirm('确认下载模板吗？', function(index){
                    var url = "${pageContext.request.contextPath }/stockOutOrder/exportFileMachineList.do"
                    window.location.href = url;
                    layer.close(index);
                });
            });

          	//"出库单详细"的行内编辑事件
            table.on('edit(tableListSub)', function(obj){
                var fieldValue = obj.value, 	//得到修改后的值
                    rowData = obj.data, 		//得到所在行所有键值
                    fieldName = obj.field; 		//得到字段
                    //首先用该行物料的id和所属供应商id去查询待发货区的数量
                    $.ajax({
                        type: "post",
                        url: "${pageContext.request.contextPath}/customer/queryWaitNumAndTotalNumByMaterialId.do",
                        data: {materiel_id:rowData.material_id},
                        success: function(waitNumAndTotalNum){
                        	if(waitNumAndTotalNum != null){
                        		var waitNumAndTotalNum = eval('(' +waitNumAndTotalNum+ ')');
                        		//fieldValue: 手动输入的值
                            	//wait_num: 待发货区的数量
                            	//total_num: 库存小箱总数
                            	//1.如果小于待发货区数量，直接减掉待发货区的数量,再减去库存的数量
                            	var res1 = waitNumAndTotalNum[0].wait_num-fieldValue;
                                if(res1 > 0){
                                	$.ajax({
                                        type: "post",
                                        url: "${pageContext.request.contextPath}/customer/updateWaitSendAreaValue.do",
                                        data: {materiel_id:rowData.material_id, materiel_num:res1},
                                        success: function(ret1){
                                        	console.log(ret1 + "success01");
                                        }
                                	});
                                	$.ajax({
                                        type: "post",
                                        url: "${pageContext.request.contextPath}/stockOutOrder/inventoryReductionURL.do",
                                        data: {materielId:rowData.material_id, materielQuantity:fieldValue},
                                        success: function(ret2){
                                        	console.log(ret2 + "success02");
                                        }
                                	});
                                } else if (res1 < 0) {
                                	$.ajax({
                                        type: "post",
                                        url: "${pageContext.request.contextPath}/customer/deleteWaitSendAreaValue.do",
                                        data: {materiel_id:rowData.material_id},
                                        success: function(ret3){
                                        	console.log(ret3 + "success03");
                                        }
                                	});
                                	$.ajax({
                                        type: "post",
                                        url: "${pageContext.request.contextPath}/stockOutOrder/inventoryReductionURL.do",
                                        data: {materielId:rowData.material_id, materielQuantity:Math.abs(fieldValue)},
                                        success: function(ret4){
                                        	console.log(ret4 + "success04");
                                        }
                                	});
                                } else {
                                	//提示可用数量不够，需要新建拆箱任务
                                	toastrStyle();
                                    toastr.warning("待发货区数量不够，需要新建拆箱任务！");
                                    setTimeout(function(){
                                        location.reload();
                                    },1000);
                                }
                        	}
                        }
                    });
                //保存修改出库单详细表的值    
                layui.use('jquery',function(){
                    var $=layui.$;
                    $.ajax({
                        type: "post",
                        url: "${pageContext.request.contextPath}/stockOutOrder/updateOutStockOrderDetailById.do",
                        data: {id:rowData.id, fieldName:fieldName, fieldValue:fieldValue },
                        success: function(zcInventoryInfoId){
                            if(zcInventoryInfoId > 0){
                                toastrStyle();
                                toastr.success("修改成功！");
                                setTimeout(function(){
                                    location.reload();
                                },1000);
                            }else{
                                toastrStyle();
                                toastr.warning("修改失败！");
                                setTimeout(function(){
                                    location.reload();
                                },1000);
                            }
                        }
                    });
                });
            });

            //"出库单详细"的行内删除事件
            table.on('tool(tableListSub)', function(obj2){
                layer.confirm('确定删除吗？', function(index){
                    var id = obj2.data.id;
                    $.ajax({
                        type:'post',
                        url:'${pageContext.request.contextPath }/stockOutOrder/deleteOutStockOrderDetailById.do',
                        data:{ "id" : id },
                        success:function(data){
                            if(data > 0){
                                toastrStyle();
                                toastr.success("删除成功！");
                                setTimeout(function(){
                                    location.reload();
                                },1000);
                            }else{
                                toastrStyle();
                                toastr.warning("删除失败！");
                                setTimeout(function(){
                                    location.reload();
                                },1000);
                            }
                        }
                    });
                    layer.close(index);
                });
            });

            /**
             * 通用表单提交(AJAX方式)（导入）
             */
            form.on('submit(uplodeform)', function (data) {
                var formData = new FormData($("#uploadform")[0]);
                $.ajax({
                    url: '${pageContext.request.contextPath}/stockOutOrder/uplodeFileReactionPlan.do' ,
                    type: 'post',
                    data: formData,
                    //async: false,
                    //cache: false,
                    dataType:'JSON',
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        if (data == 1) {
                            toastr.success("文件导入成功！");
                            setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                                window.location.reload();
                                $("#reset").click();
                            },1000);
                        }else if(data == -1){
                            toastr.warning("导入的数据不符合导入条件！");
                        }else{
                            toastr.warning("文件格式异常，文件导入失败！");
                        }
                    },
                    error: function (data) {
                        toastr.error("文件格式异常，文件导入失败！");
                    }
                })
                return false;
            });

			/**
			 * 提交出库单(AJAX方式)(新增)
			 */
			form.on('submit(addForm)', function (data) {
				$.ajax({
					url : '${pageContext.request.contextPath}/stockOutOrder/addStockOutOrder.do',
					data: $("#addFormID").serialize(),
					cache : false,
					type : "post",
				}).done(
					function(res) {
						if (res > 0) {
							/* —————————————— */
							toastrStyle();
							toastr.success('新增成功！');
							setTimeout(function(){
								location.reload();
							},1000);
							/* —————————————— */
						}
					}
				).fail(
					function(res) {
						toastrStyle();
						toastr.error('新增失败！');
						setTimeout(function(){
							location.reload();
						},1000);
					}
				)
				return false;
			});
			
			/**
			 * 提交出库单(AJAX方式)(编辑)
			 */
			form.on('submit(updateForm)', function (data) {
				$.ajax({
					url : '${pageContext.request.contextPath}/stockOutOrder/updateStockOutOrder.do',
					data: $("#updateFormID").serialize(),
					cache : false,
					type : "post",
				}).done(
					function(res) {
						if (res > 0) {
							/* —————————————— */
							toastrStyle();
							toastr.success('编辑成功！');
							setTimeout(function(){
								location.reload();
							},1000);
							/* —————————————— */
						}
					}
				).fail(
					function(res) {
						toastrStyle();
						toastr.error('编辑失败！');
						setTimeout(function(){
							location.reload();
						},1000);
					}
				)
				return false;
			});

			/**
			 * 提交待发货区和库存物料(AJAX方式)(新增)
			 */
			form.on('submit(addBtn)', function (data) {
				//获取出库单id
				var checkStatus1 = table.checkStatus('contenttable')
	      		var data1 = checkStatus1.data;
				var out_stock_num_id = data1[0].id;
				//供应商id
				var checkStatus2 = table.checkStatus('customerList')
	      		var data2 = checkStatus2.data;
				var customer_id = data2[0].id;
				//获取供应商的物料明细中的数据
				//var oldData = table.cache['contenttable2'];
				var checkStatus3 = table.checkStatus('contenttable2')
				var data3 = checkStatus3.data;
				if(data3.length == 0){
					toastr.warning("请选择物料！");
				} else {
					var affct = 0;
					//根据出库单的id和物料id查询该出库单是否存在该物料
					for (var i = 0; i < data3.length; i++) {
						var material_id = data3[i].id;
						$.ajax({
		                    url: '${pageContext.request.contextPath}/stockOutOrder/queryExistMaterial.do' ,
		                    type: 'post',
		                    data: {out_stock_num_id:out_stock_num_id, material_id:material_id, customer_id:customer_id},
		                    async: false,
		                    dataType:'JSON',
		                    success: function (result) {
		                    	if (result > 0) {
		                    		toastr.warning("记录已经存在，不能重复添加");
		                    	} else {
	    			            	//添加收货明细
	    							$.ajax({
	    			                    url: '${pageContext.request.contextPath}/stockOutOrder/addStockOutOrderDetail.do' ,
	    			                    type: 'post',
	    			                    data: {out_stock_num_id:out_stock_num_id, material_id:material_id, customer_id:customer_id},
	    			                    async: false,
	    			                    dataType:'JSON',
	    			                    success: function (result) {
	    			                    	if (result > 0) {
	    								 		affct = affct + 1;
	    								 		if(affct > 0) {
    												toastr.success('新增成功！');
    												setTimeout(function(){
    													location.reload();
    												},1000);
    											}else {
    												toastr.error('新增失败！');
    											}
	    			                    	}
	    			            		}
	    							});
		                    	}
		            		}
						});
					}
					/* $.ajax({
	                    url: '${pageContext.request.contextPath}/stockOutOrder/queryExistMaterial.do' ,
	                    type: 'post',
	                    data: {out_stock_num_id:out_stock_num_id, material_id:material_id, customer_id:customer_id},
	                    async: false,
	                    dataType:'JSON',
	                    success: function (result) {
	                    	if (result > 0) {
	                    		toastr.warning("记录已经存在，不能重复添加");
	                    	} else {
	                    		for (var i = 0; i < data3.length; i++) {
	    							var material_id = data3[i].id;
	    							//alert("物料id"+material_id)
	    			            	//添加收货明细
	    							$.ajax({
	    			                    url: '${pageContext.request.contextPath}/stockOutOrder/addStockOutOrderDetail.do' ,
	    			                    type: 'post',
	    			                    data: {out_stock_num_id:out_stock_num_id, material_id:material_id, customer_id:customer_id},
	    			                    async: false,
	    			                    dataType:'JSON',
	    			                    success: function (result) {
	    			                    	if (result > 0) {
	    								 		  affct = affct + 1;
	    			                    	}
	    			            		}
	    							});
	    						}
	                    	}
	            		}
					}); */
				}
				return false;
			});
			
			//根据仓库id查询管理员id，再查询user的姓名、电话
		    form.on('select(warehouse_id)', function(data) {
		    	$.ajax({
		            type: 'POST',
		            url: '${pageContext.request.contextPath}/stockOutOrder/queryWarehouseById.do',
		            data: {id:data.value},
		            //dataType: 'json',
		            //async: false,
		            success: function (data1){
		            	if(data1 != null){
		            		var warehouse = eval('(' +data1+ ')');
			            	$('#warehouse_address').val(warehouse[0].warehouse_address);
			            	$.ajax({
					            type: 'POST',
					            url: '${pageContext.request.contextPath}/stockOutOrder/queryUserById.do',
					            data: {id:warehouse[0].staff_id},
					            //dataType: 'json',
					            //async: false,
					            success: function (data2){
					            	if(data2 != null){
					            		var user = eval('(' +data2+ ')');
						            	$('#userName').val(user[0].userName);
						            	$('#phone').val(user[0].phone);
					            	}
					            }
					        });
		            	}
		            }
		        });
		    });
			
		  	//根据客户id查询联系人id，再查询负责人的姓名和电话
		    form.on('select(customer_id)', function(data){
				$.ajax({
                    type: 'POST',
                    url: '${pageContext.request.contextPath}/stockOutOrder/queryCustomerById.do',
                    data: {id:data.value},
                    //dataType: 'json',
                    //async: false,
                    success: function (data1){
                    	if(data1 != null){
		            		var customer = eval('(' +data1+ ')');
			            	$('#customer_adress').val(customer[0].customer_adress);
			            	$.ajax({
					            type: 'POST',
					            url: '${pageContext.request.contextPath}/stockOutOrder/queryContactsById.do',
					            data: {id:customer[0].contacts_id},
					            //dataType: 'json',
					            //async: false,
					            success: function (data2){
					            	if(data2 != null){
					            		var contacts = eval('(' +data2+ ')');
						            	$('#contacts_name').val(contacts[0].contacts_name);
						            	$('#contacts_tel').val(contacts[0].contacts_tel);
					            	}
					            }
					        });
		            	}
                    }
                });
			})
			
			/**
			 * 新增表单校验 
			 */
			form.verify({
				//value：表单的值item：表单的DOM对象
				create_date: function(value, item){
					if(value == ''){
						return '创建日期不能为空';
					}
				},
				source: function(value, item){
					if(value == ''){
						return '仓库类型不能为空';
					}
				},
				warehouse_id: function(value, item){
					if(value == ''){
						return '仓库名称不能为空';
					}
				},
				customer_id: function(value, item){
					if(value == ''){
						return '主机厂名称不能为空';
					}
				},
			});

			//新增
            $("#add").click(function(){
            	//时间戳
        		var timestamp = (new Date()).getTime();
                layer.open({
                    type: 1 					//Page层类型
                    ,area: ['680px', ''] 	//宽  高
                    ,title: '新增'
                    ,shade: 0.6 				//遮罩透明度
                    ,maxmin: true 				//允许全屏最小化
                    ,anim: 1 					//0-6的动画形式，-1不开启
                    ,content:
                        '<div id="addDivID">'+
							'<form class="layui-form" id="addFormID">'+
								'<xblock>'+
									'<table>'+
										'<tr>'+
											'<td><label class="layui-form-label">出库单号</label></td>'+
											'<td>'+
												'<input readonly class="layui-input" id="out_stock_num" name="out_stock_num" value="CKDH-'+timestamp+'" style="color: gray; width: 190px">'+
											'</td>'+
											'<td><label class="layui-form-label">创建日期</label></td>'+
											'<td>'+
												'<input class="layui-input" id="create_date" name="create_date" lay-verify="create_date" style="width: 190px; display:inline" placeholder="请选择">'+
												'<div class="layui-inline" style="margin-top: 10px;">'+
		                                            '<span style="color:red; font-size: 24px; margin-left: 4px">*</span>'+
		                                        '</div>'+
											'</td>'+
										'</tr>'+
										'<tr style="height: 10px"></tr>'+
										'<tr>'+
											'<td><label class="layui-form-label">仓库类型</label></td>'+
											'<td>'+
												'<div style="width: 190px; float: left;">' +
													'<select id="source" name="source" lay-verify="source">' +
														'<option value="">请选择</option>' +
														'<option value="0">良品库</option>' +
														'<option value="1">不良品库</option>' +
													'</select>'+
			                                    '</div>'+
			                                    '<div style="margin-top: 12px;">'+
			                                        '<span style="color:red; font-size: 24px; margin-left: 4px">*</span>'+
			                                    '</div>'+
											'</td>'+
											'<td><label class="layui-form-label">仓库名称</label></td>'+
											'<td>'+
												'<div style="width: 190px; float: left;">' +
													'<select id="warehouse_id" name="warehouse_id" lay-verify="warehouse_id" lay-filter="warehouse_id">' +
														'<option value="">请选择</option>' +
													'</select>'+
			                                    '</div>'+
			                                    '<div style="margin-top: 12px;">'+
			                                        '<span style="color:red; font-size: 24px; margin-left: 4px">*</span>'+
			                                    '</div>'+
											'</td>'+
										'</tr>'+
										'<tr style="height: 10px"></tr>'+
										'<tr>'+
											'<td><label class="layui-form-label">管理员姓名</label></td>'+
											'<td>'+
												'<input class="layui-input" id="userName" name="userName" style="width: 190px; display:inline" placeholder="请选择">'+
											'</td>'+
											'<td><label class="layui-form-label">管理员电话</label></td>'+
											'<td>'+
												'<input class="layui-input" id="phone" name="phone" style="width: 190px; display:inline" placeholder="请选择">'+
											'</td>'+
										'</tr>'+
										'<tr style="height: 10px"></tr>'+
										'<tr>'+
											'<td><label class="layui-form-label">仓库地址</label></td>'+
											'<td>'+
												'<input class="layui-input" id="warehouse_address" name="warehouse_address" style="width: 190px; display:inline" placeholder="请选择">'+
											'</td>'+
											'<td><label class="layui-form-label">主机厂名称 </label></td>'+
											'<td>'+
												'<div style="width: 190px; float: left;">' +
			                                        '<select id="customer_id" name="customer_id" lay-verify="customer_id" lay-filter="customer_id">' +
			                                            '<option value="">请选择</option>' +
			                                        '</select>'+
			                                    '</div>'+
			                                    '<div style="margin-top: 12px;">'+
			                                        '<span style="color:red; font-size: 24px; margin-left: 4px">*</span>'+
			                                    '</div>'+
											'</td>'+
										'</tr>'+
										'<tr style="height: 10px"></tr>'+
										'<tr>'+
											'<td><label class="layui-form-label">负责人</label></td>'+
											'<td>'+
												'<input class="layui-input" id="contacts_name" name="contacts_name" style="width: 190px; display:inline">'+
											'</td>'+
											'<td><label class="layui-form-label">负责人电话</label></td>'+
											'<td>'+
												'<input class="layui-input" id="contacts_tel" name="contacts_tel" style="width: 190px; display:inline">'+
											'</td>'+
										'</tr>'+
                        				'<tr style="height: 10px"></tr>'+
										'<tr>'+
											'<td><label class="layui-form-label">客户地址</label></td>'+
											'<td colspan="3">'+
												'<input class="layui-input" id="customer_adress" name="customer_adress" style="width: 490px; display:inline">'+
											'</td>'+
										'</tr>'+
									'</table>'+
								'</xblock>'+
								'<xblock>'+
									'<button class="layui-btn layui-btn-blue" id="subBtn" lay-submit lay-filter="addForm" style="margin-left:250px; margin-bottom: 10px">提交</button>'+
									'&emsp;&emsp;&emsp;&emsp;<button class="layui-btn layui-btn-primary" style="margin-bottom: 10px">取消</button>'+
								'</xblock>'+
								'</table>'+
							'</form>'+
                    	'</div>'
					,cancel : function(){
						//数组置空
						//hideArr = [];
					}
                    ,success: function(){
                    	//查找所有仓库
                    	$.ajax({ 
                            type: 'POST',
                            url: '${pageContext.request.contextPath}/warehouse/queryAllWarehouse.do',
                            dataType: 'json',
                            async: false,
                            success: function (datas){
                                for (var i = 0; i < datas.length; i++) {
                                	$("#warehouse_id").append("<option value='"+ datas[i].id +"'>"+ datas[i].warehouse_name +"</option>");
                                }
                            }
                        });
                    	//查找所有客户/主机厂
                    	$.ajax({ 
                            type: 'POST',
                            url: '${pageContext.request.contextPath}/stockOutOrder/queryAllCustomerByType1.do',
                            dataType: 'json',
                            async: false,
                            success: function (datas){
                                for (var i = 0; i < datas.length; i++) {
                                	$("#customer_id").append("<option value='"+ datas[i].id +"'>"+ datas[i].customer_name +"</option>");
                                }
                            }
                        });
                        laydate.render({
                            elem: '#create_date'
                        });
                        form.render();
                    }
                });
			});

          	//查询所有的供应商
    		$('#add1').click(function(){
    			$("#customerMaterielList").hide();
    			layer.open({
    				type: 1 					//Page层类型
    				,area: ['1000px', '500px'] 	//宽  高
    				,title: '客户的物料列表'
    				,shade: 0.1 				//遮罩透明度
    				,shadeClose: true 			//点击遮罩关闭
    				,maxmin: true 				//允许全屏最小化
    				,anim: 1 					//0-6的动画形式，-1不开启
    				,content: $("#addTwoFormIDDiv")
    				,success: function () {
    					//1.查询待发货区
    					layui.use(['table'], function(){
    						var table = layui.table;
    						table.render({
    							elem: '#customerList'
    							,url:'${pageContext.request.contextPath}/customer/queryCustomerCriteriaByType.do'
    							,title: '客户列表'
    							,limits:[10,20,30]
    							,cols: [[
    							  	{type: 'checkbox', fixed: 'left', },
    							  	{field:'customer_name', title:'供应商姓名', align:'center'},
    							  	{field:'customer_num', title:'编号', align:'center'},
    							  	{field:'customer_region', title:'供应商所在地区', align:'center'},
    							  	{field:'customer_adress', title:'供应商地址', align:'center'},
    							  	{field:'customer_email', title:'供应商邮箱', align:'center'},
    							  	{field:'customer_zipcode', title:'供应商邮编', align:'center'}
    							]]
    							,page: true
    							,done : function(){
    				                $('th').css({
    				                    'background-color': '#009688', 'color': '#fff','font-weight':'bold',
    				                    'font-size': 10,
    				                })
    				            }
    						});
    			        });
    				}
    				,end: function () {
    					var formDiv = document.getElementById('inventoryInfoDiv');
    					formDiv.style.display = '';
    					layer.closeAll();
    				}
    			});
    		});
			
			//"出库单"批量删除
			$("#dels").click(function(){
				var rowData = table.checkStatus('contenttable');
				var data = rowData.data;
				var idArr = new Array();
				if(data.length == 0){
					toastrStyle();
					toastr.warning("请至少选择一条记录！");
				} else {
					for(var i=0;i < data.length;i++){
						idArr[i] = data[i].id;
						console.log(data[i].id);
					}
					layer.confirm('确定删除吗？', function(index){
	    				$.ajax({
	    			    	type:'post',
	    			    	url:'${pageContext.request.contextPath }/stockOutOrder/deleteOutStockOrderById.do',
	    			    	data:{"idArr" : idArr},
	    			    	success:function(data){
	    			    		if(data > 0){
	    			    			toastrStyle();
	    			    			toastr.success("删除成功！");
	    			    			setTimeout(function(){  
	    								window.location.reload();  
	    							},1000);
	    			    		}else{
	    			    			toastrStyle();
	    			    			toastr.error("删除失败！");
	    			    			setTimeout(function(){  
	    								window.location.reload();  
	    							},1000);
	    			    		}
	    			    	}
	    			    })
	    		    	layer.close(index);
	    			});
				}
			});
			
			//"出库单详细"批量删除
			$("#dels1").click(function(){
				var rowData = table.checkStatus('contenttable1');
				var datas = rowData.data;
				var idArr = new Array();
				if(datas.length == 0){
					toastrStyle();
					toastr.warning("请至少选择一条记录！");
				} else {
					for(var i=0;i < datas.length;i++){
						idArr[i] = datas[i].id;
						console.log(datas[i].id);
					}
					layer.confirm('确定删除吗？', function(index){
	    				$.ajax({
	    			    	type:'post',
	    			    	url:'${pageContext.request.contextPath }/stockOutOrder/deleteOutStockOrderDetailById.do',
	    			    	data:{"idArr" : idArr},
	    			    	success:function(data){
	    			    		if(data > 0){
	    			    			toastrStyle();
	    			    			toastr.success("删除成功！");
	    			    			setTimeout(function(){  
	    								window.location.reload();  
	    							},1000);
	    			    		}else{
	    			    			toastrStyle();
	    			    			toastr.error("删除失败！");
	    			    			setTimeout(function(){  
	    								window.location.reload();  
	    							},1000);
	    			    		}
	    			    	}
	    			    })
	    		    	layer.close(index);
	    			});
				}
			});
		});
		
		//导入
		function uploadExcel(){
			layer.open({
                type: 1 		//Page层类型
                ,area: ['410px', '200px'] //宽  高
                ,title: '导入'
                ,shade: 0.6 	//遮罩透明度
                ,maxmin: true //允许全屏最小化
                ,anim: 1 		//0-6的动画形式，-1不开启
                ,content: $('#importDiv')
                ,end: function () {
                    var formDiv = document.getElementById('importDiv');
                    formDiv.style.display = '';
                }
            });
		}

        //日期格式转换
        function dateToStr(date) {
            var time = new Date(date.time);
            var y = time.getFullYear();
            var M = time.getMonth() + 1;
            M = M < 10 ? ("0" + M) : M;
            var d = time.getDate();
            d = d < 10 ? ("0" + d) : d;
            var str = y + "-" + M + "-" + d;
            return str;
        }
        
      	//日期格式转换
		function date2String(timestamp){
			var d = new Date(timestamp);
			var date = (d.getFullYear()) + "-" + 
		       (d.getMonth() + 1<10?"0"+(d.getMonth() + 1):d.getMonth() + 1) + "-" +
		       (d.getDate()<10?"0"+d.getDate():d.getDate());
			return date;
		}
      	
		function formatDate(time) { 
			var d = new Date(time);
        	var dformat = [ d.getFullYear(),
        	checkTime(d.getMonth() + 1), checkTime(d.getDate()) ].join('-');
        	return dformat;
    	};
    	
   	  	//修改时间戳查询时间
		function checkTime(n) {
			return n < 10 ? '0' + n : n;
   	  	};
   	 toastrStyle()
	</script>
</body>
</html>